const Ali = require('aliyun-sdk');
const cfg = require('./config');

class Fetcher {
  constructor() {
    this._sls = new Ali.SLS({
      accessKeyId: cfg.accessKeyId,
      secretAccessKey: cfg.accessKeySecret,
      endpoint: cfg.endpoint,

      // 这是 sls sdk 目前支持最新的 api 版本, 不需要修改
      apiVersion: '2015-06-01',
    });

    const fromTo = this._getFromTo(cfg);

    this._opt = {
      projectName: cfg.project,
      logStoreName: cfg.logStore,
      from: fromTo.from,
      to: fromTo.to,
      query: cfg.query,
      offset: 0,
      // line: 2, // for test
    };
  }

  getLog(offset) {
    return new Promise((resolve, reject) => {
      this._opt.offset = offset;
      this._sls.getLogs(this._opt, (err, data) => {
        if (err) reject(err);
        resolve(data.body);
      });
    });
  }

  _getFromTo({ lastHours, from, to }) {
    if (lastHours) {
      const to = Math.floor(Date.now() / 1000);
      const from = to - lastHours * 60 * 60;
      return { from, to };
    } else if (from && to) {
      return {
        from: Math.floor(new Date(from).getTime() / 1000),
        to: Math.floor(new Date(to).getTime() / 1000),
      };
    }
    throw new Error('please input time range');
  }
}

module.exports = Fetcher;
